<!--
 * @Author: C.
 * @Date: 2023-04-13 11:05:19
-->
<template>
  <Block title="附件" :wrapper="false" :loading="loadingRef">
    <BasicTable @register="registerTable">
      <template #toolbar v-if="!props.readOnly">
        <JUpload @success="upLoadSuccess" type="file">
          <a-button type="primary"> 上传 </a-button>
        </JUpload>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:eye-outlined',
                tooltip: '预览',
                onClick: toReview.bind(null, record),
                disabled: canReview(record.FileType),
              },
              {
                icon: 'ant-design:download-outlined',
                tooltip: '下载',
                onClick: toDownload.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                tooltip: t('common.delText'),
                popConfirm: {
                  title: t('common.isDel'),
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
                ifShow: !props.readOnly,
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <Image
      :style="{ display: 'none' }"
      :preview="{
        visible,
        onVisibleChange: setVisible,
      }"
      :src="src"
    />
  </Block>
</template>

<script lang="ts" setup name="AuditFlow">
  import { PropType, unref, watch, ref, computed } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useAppDetailsTable } from '/~/hooks/help/useAppTable';
  import { Image } from 'ant-design-vue';
  import { getTableMaps } from '/~/utils/help/createFields';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { fileAttachment } from '/@/api/work/system/file';
  import { JUpload } from '/~/components/Upload';
  import { downloadByUrl, isImage, isPDF, viewPDF } from '/~/utils/file/index';
  import { getImgUrl } from '/@/jv_package/utils/system/index';
  const { t } = useI18n();
  const visible = ref<boolean>(false);
  const src = ref<string>('');
  const loadingRef = ref<boolean>(false);
  const setVisible = (value): void => {
    visible.value = value;
  };
  const props = defineProps({
    fileId: String as PropType<string>,
    readOnly: {
      type: Boolean as PropType<boolean>,
      default: false,
    },
  });
  const emit = defineEmits(['change', 'file-change']);
  const [
    registerTable,
    { setTableData, deleteTableDataRecord, getDataSource, insertTableDataRecord },
  ] = useAppDetailsTable({
    title: '附件',
    columns: getTableMaps([
      {
        dataIndex: 'FileName',
        title: '文件名称',
      },
      { dataIndex: 'FileType', title: '类型' },
      {
        dataIndex: 'FileSize',
        title: '文件大小',
      },
      {
        dataIndex: 'FileUrl',
        title: '附件地址',
        defaultHidden: true,
      },
      'Creator',
      'CreationDate',
    ]),
    tableSetting: {
      import: props.readOnly,
      export: props.readOnly,
    },
    // rowKey: 'CraftId',
    dataSource: [],
    actionColumn: {
      width: 160,
    },
  });
  function handleDelete(record: Recordable) {
    // 通过绑定的rowKey删除
    deleteTableDataRecord(unref(record).key);
  }
  function toDownload(record: Recordable) {
    downloadByUrl({
      fileName: record.FileName,
      params: {
        FileUrl: record.FileUrl,
      },
    });
  }
  const canReview = computed(() => {
    return (FileType) => {
      return !(isImage(FileType) || isPDF(FileType));
    };
  });
  // toReview
  function toReview(record: Recordable) {
    if (isImage(record.FileType)) {
      src.value = getImgUrl('test');
      setVisible(true);
    } else if (isPDF(record.FileType)) {
      viewPDF(record.FileUrl);
    }
  }
  function upLoadSuccess(fileObj: Recordable) {
    insertTableDataRecord(fileObj);
  }
  async function fetchData(OwnerId: string) {
    loadingRef.value = true;
    let res = await fileAttachment({ OwnerId });
    setTableData(res.Items || []);
    loadingRef.value = false;
  }
  watch(
    () => unref(props).fileId,
    (e) => {
      e && fetchData(e);
    },
  );
  watch(
    () => getDataSource().length,
    () => {
      let data = getDataSource();
      emit('change', data);
      emit(
        'file-change',
        data.map((item) => item.FileUrl),
      );
    },
    { immediate: true },
  );
</script>
<style lang="less" scoped></style>
